const AdminModel = require('../db/models/admin');

class AdminService {
    async addAdmin(adminInfo){
        const { username } = adminInfo;

        const res = await AdminModel.findOne({
            where: { username },
        });

        if(res){
            return await AdminModel.update(adminInfo, {
                where: { username },
            })
        } else {
            return await AdminModel.create(adminInfo);
        }
    }

    // 登录校验
    async login(userInfo) {
        const { username, password } = userInfo;

        // 判断用户名是否存在
        const usernameExist = await AdminModel.findOne({
            where: { username }
        });

        if(!usernameExist){ // 不存在
            return 10003;
        } 

        // 比较密码
        const dbPassword = usernameExist.get('password');

        // 两个加密密码进行比较
        if(password !== dbPassword) {
            return 10004;
        }

        // 最后返回登录成功
        const uid = usernameExist.get('id');

        return {
            uid,
            username,
        };
    }
}

module.exports = new AdminService();